package com.googlecode.maninman.framework.servlet;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

import net.rubyeye.xmemcached.MemcachedClient;

public class WrapperedRequest extends HttpServletRequestWrapper{
	private String sessionId;
//	private MemcachedClient memcachedClient;
	
	public WrapperedRequest(HttpServletRequest request) {
		super(request);
	}

	public String getRequestedSessionId() {
		if (!isRequestedSessionIdFromCookie() && !isRequestedSessionIdFromURL()) {
			synchronized (WrapperedRequest.class) {
				sessionId = Long.toHexString(System.nanoTime());
			}
		}
		return sessionId;
	}

	public HttpSession getSession() {
		return getSession(true);
	}

	public HttpSession getSession(boolean flag) {
		HttpSession session = null;
		if (!flag) {
			//return memcachedClient.get(sessionId);
		}
		if (session != null)
			return session;
		return new StandardSession(sessionId, getServletContext());
	}

	public boolean isRequestedSessionIdFromCookie() {
		Cookie[] cookies = super.getCookies();
		for (Cookie cookie : cookies) {
			if (Definitions.SESSIONID.equals(cookie.getName())) {
				sessionId = cookie.getValue();
				return true;
			}
		}
		return false;
	}

	public boolean isRequestedSessionIdFromURL() {
		String sessionId = super.getParameter(Definitions.SESSIONID);
		if (sessionId == null) return false;
		this.sessionId = sessionId;
		return true;
	}

	public boolean isRequestedSessionIdValid() {
		// TODO
		return super.isRequestedSessionIdValid();
	}
	
	
}
